import { Response } from 'express';
import { AuthenticatedRequest } from '../types';
import { EvaluationDocument } from '../models/evaluationModel';
import { EvaluationStandards, DefaultEvaluationSettings } from '../config/evaluationConfig';

// 添加批注
export const addAnnotation = async (req: AuthenticatedRequest, res: Response) => {
  try {
    const { evaluationId } = req.params;
    const { content, type, position } = req.body as {
      content: string;
      type: keyof typeof EvaluationStandards.annotationTypes;
      position: { start: number; end: number; };
    };

    const evaluation = await EvaluationModel.findById(evaluationId);

    if (!evaluation) {
      return res.status(404).json({ message: '评价记录不存在' });
    }

    // 验证批注类型
    if (!EvaluationStandards.annotationTypes[type]) {
      return res.status(400).json({ message: '无效的批注类型' });
    }

    // 添加新批注
    evaluation.annotations.push({
      content,
      type,
      position,
      createdBy: req.user!.userId,
      createdAt: new Date()
    });

    await evaluation.save();

    res.json({
      message: '批注添加成功',
      annotation: evaluation.annotations[evaluation.annotations.length - 1]
    });
  } catch (error) {
    res.status(500).json({ message: '添加批注失败', error });
  }
};

// 获取批注列表
export const getAnnotations = async (req: AuthenticatedRequest, res: Response) => {
  try {
    const { evaluationId } = req.params;
    const evaluation = await EvaluationModel.findById(evaluationId)
      .select('annotations')
      .populate('annotations.createdBy', 'username');

    if (!evaluation) {
      return res.status(404).json({ message: '评价记录不存在' });
    }

    res.json(evaluation.annotations);
  } catch (error) {
    res.status(500).json({ message: '获取批注失败', error });
  }
};

// 更新批注
export const updateAnnotation = async (req: AuthenticatedRequest, res: Response) => {
  try {
    const { evaluationId, annotationId } = req.params;
    const { content } = req.body;

    const evaluation = await EvaluationModel.findById(evaluationId);

    if (!evaluation) {
      return res.status(404).json({ message: '评价记录不存在' });
    }

    // 找到对应的批注
    const annotationIndex = evaluation.annotations.findIndex(
      (a: any) => a._id && a._id.toString() === annotationId
    );

    if (annotationIndex === -1) {
      return res.status(404).json({ message: '批注不存在' });
    }

    const annotation = evaluation.annotations[annotationIndex];

    // 验证权限
    if (annotation.createdBy.toString() !== req.user!.userId) {
      return res.status(403).json({ message: '无权修改此批注' });
    }

    // 更新批注内容
    annotation.content = content;
    await evaluation.save();

    res.json({
      message: '批注更新成功',
      annotation
    });
  } catch (error) {
    res.status(500).json({ message: '更新批注失败', error });
  }
};

// 删除批注
export const deleteAnnotation = async (req: AuthenticatedRequest, res: Response) => {
  try {
    const { evaluationId, annotationId } = req.params;

    const evaluation = await EvaluationModel.findById(evaluationId);

    if (!evaluation) {
      return res.status(404).json({ message: '评价记录不存在' });
    }

    // 找到对应的批注
    const annotationIndex = evaluation.annotations.findIndex(
      (a: any) => a._id && a._id.toString() === annotationId
    );

    if (annotationIndex === -1) {
      return res.status(404).json({ message: '批注不存在' });
    }

    const annotation = evaluation.annotations[annotationIndex];

    // 验证权限
    if (annotation.createdBy.toString() !== req.user!.userId) {
      return res.status(403).json({ message: '无权删除此批注' });
    }

    // 删除批注
    evaluation.annotations.splice(annotationIndex, 1);
    await evaluation.save();

    res.json({ message: '批注删除成功' });
  } catch (error) {
    res.status(500).json({ message: '删除批注失败', error });
  }
};

// 批量添加批注
export const batchAddAnnotations = async (req: AuthenticatedRequest, res: Response) => {
  try {
    const { evaluationId } = req.params;
    const { annotations } = req.body;

    const evaluation = await EvaluationModel.findById(evaluationId);

    if (!evaluation) {
      return res.status(404).json({ message: '评价记录不存在' });
    }

    // 验证批注数量限制
    if (evaluation.annotations.length + annotations.length > 
        DefaultEvaluationSettings.annotationLimit) {
      return res.status(400).json({ message: '超出批注数量限制' });
    }

    // 批量添加批注
    const newAnnotations = annotations.map((annotation: any) => ({
      ...annotation,
      createdBy: req.user!.userId,
      createdAt: new Date()
    }));

    evaluation.annotations.push(...newAnnotations);
    await evaluation.save();

    res.json({
      message: '批量添加批注成功',
      annotations: newAnnotations
    });
  } catch (error) {
    res.status(500).json({ message: '批量添加批注失败', error });
  }
};

// 按类型获取批注统计
export const getAnnotationStats = async (req: AuthenticatedRequest, res: Response) => {
  try {
    const { evaluationId } = req.params;
    
    const evaluation = await EvaluationModel.findById(evaluationId)
      .select('annotations');

    if (!evaluation) {
      return res.status(404).json({ message: '评价记录不存在' });
    }

    // 统计各类型批注数量
    const stats = evaluation.annotations.reduce((acc: Record<string, number>, curr: any) => {
      acc[curr.type] = (acc[curr.type] || 0) + 1;
      return acc;
    }, {});

    res.json({
      total: evaluation.annotations.length,
      byType: stats
    });
  } catch (error) {
    res.status(500).json({ message: '获取批注统计失败', error });
  }
};
